package com.yskj.tms.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yskj.tms.common.UsersById;
import com.yskj.tms.entity.*;
import com.yskj.tms.service.ShipInfoService;
import com.yskj.tms.util.FiledUtil;
import com.yskj.tms.util.RandomUtil;
import com.yskj.tms.util.StringUtil;
import net.sf.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.sql.Timestamp;
import java.util.*;

/**
 * Created by Administrator on 2018/4/19.
 */
@Controller
public class ShipInfoController {
    @Autowired
    private ShipInfoService shipInfoService;


    private UsersById users = new UsersById();

    @RequestMapping("/maps.do")
    public ModelAndView toMaps() throws  Exception{
        ModelAndView mav = new ModelAndView("/map/maps");
        return mav;
    }

    @RequestMapping("/bigmaps.do")
    public ModelAndView toBigmaps() throws  Exception{
        ModelAndView mav = new ModelAndView("/map/bigmaps");
        return mav;
    }

    @RequestMapping(value = "/selectShipAndDevice.do")
    @ResponseBody
    public void selectShipinfoAndDeviceinfo(HttpServletResponse response, HttpServletRequest request, @RequestParam(value = "shipname")String shipname) throws Exception{
        response.setCharacterEncoding("UTF-8");
        PrintWriter printWriter = response.getWriter();
        int ustats=2;
        Map map = new HashMap<>();
        List list1 = new ArrayList();
        List<ShipInfo> list = shipInfoService.selectShipInfoListByQuery(users.getUserid(request),ustats);
        if (list != null && list.size()>0){
            for (int i=0; i<list.size();i++){
                list1.add(list.get(i).getShipid());
            }
            map.put("list",list1);
            map.put("shipname",shipname);
            List<ShipInfo> shipList = shipInfoService.selectShipAndDeviceByQuery(map);
            printWriter.print(StringUtil.toJson(shipList));
            printWriter.flush();
            printWriter.close();
        }else{
            printWriter.print(StringUtil.toJson(false));
            printWriter.flush();
            printWriter.close();
        }
    }



    @RequestMapping(value = "/selectShipAndDeviceShowMap.do")
    @ResponseBody
    public void selectShipAndDeviceShowMap(HttpServletResponse response, HttpServletRequest request, @RequestParam(value = "emtiy")int emtiy) throws Exception{
        response.setCharacterEncoding("UTF-8");
        PrintWriter printWriter = response.getWriter();
        Map map = new HashMap<>();
        map.put("userid",users.getUserid(request));
        map.put("ustats",2);
        if (emtiy == 2){
            map.put("isonline",1);
        }else{
            map.put("isonline",0);
            map.put("isemtiy",emtiy);
        }
        List<ShipInfo> shipList = shipInfoService.selectShipinfoAndDeviceByIsonlineOrIsemtiy(map);
        if (shipList!=null && shipList.size()>0){
            printWriter.print(StringUtil.toJson(shipList));
            printWriter.flush();
            printWriter.close();
        }else{
            printWriter.print(StringUtil.toJson(false));
            printWriter.flush();
            printWriter.close();
        }
    }


    @RequestMapping("/dashboard.do")
    public ModelAndView todashboard() throws  Exception{
        ModelAndView mav = new ModelAndView("/dashboard/dashboard");
        return mav;
    }
//    //详情页面
//    @RequestMapping("/shipDetail.do")
//    public ModelAndView toShipDetail() throws  Exception{
//        ModelAndView mav = new ModelAndView("/ship/shipDetail");
//        return mav;
//    }

    @RequestMapping("/searchShip.do")
    public ModelAndView toSearchShip(@RequestParam(value = "emtiy")int emtiy) throws  Exception{
        ModelAndView mav = new ModelAndView("/ship/shipSearchInfo");
        mav.addObject("emtiy",emtiy);
        return mav;
    }

    @RequestMapping(value = "/searchShipInfos.do")
    @ResponseBody
    public String searchShipInfo(HttpServletRequest request,@RequestParam(value = "page") int page,@RequestParam(value = "limit") int size,@RequestParam(value = "emtiy") int isemtiy) throws Exception{
        List<ShipInfo> shipInfosList = new ArrayList<ShipInfo>();
        int ustats =2;
        int count=0;
        if (isemtiy==2){
            shipInfosList=  shipInfoService.selectShipList(users.getUserid(request),page,size,ustats);
            count = shipInfoService.selectShipinfoCount(users.getUserid(request),ustats);
        }else if(isemtiy==3){
            int isonline =1;
            shipInfosList=  shipInfoService.selectShipListIsonline(users.getUserid(request),page,size,isonline,ustats);
            count = shipInfoService.selectShipInfoByIsonlneCount(users.getUserid(request),isonline,ustats);
        } else{
            int isonline =0;
            shipInfosList=  shipInfoService.selectShipListIsemtiy(users.getUserid(request),page,size,isemtiy,isonline,ustats);
            count = shipInfoService.selectShipinfoByIsemityCount(users.getUserid(request),isemtiy,isonline,ustats);
        }
        for(int i=0;i<shipInfosList.size();i++){
            String cname = FiledUtil.getAdd(shipInfosList.get(i).getDeviceInfo().getLongitude(),shipInfosList.get(i).getDeviceInfo().getLatitude());
            shipInfosList.get(i).getDeviceInfo().setCname(cname);
        }
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("code","");
        map.put("msg","");
        map.put("count",count);
        map.put("data",shipInfosList);
        return new ObjectMapper().writeValueAsString(map);
    }


    //修改运输计划中查询船舶信息
    @RequestMapping(value = "/searchShipInfoNotByShipid.do")
    @ResponseBody
    public String searchShipInfoNotByShipid(HttpServletRequest request) throws Exception{
        //HttpSession session = request.getSession();
        Map map =new HashMap();
        int pageNum=1;
        //int userid = (int)session.getAttribute("userid");
        String shipid = request.getParameter("shipid");
        if (!StringUtil.isEmpty(shipid)&&shipid!=""){
            JSONArray jsonArray = JSONArray.fromObject(request.getParameter("shipid"));
            List<Integer> shipidList = new ArrayList<Integer>();
            for (int i=0;i<jsonArray.size();i++){
                shipidList.add(Integer.parseInt(jsonArray.getJSONObject(i).getString("shipid")));
            }
            map.put("list",shipidList);
        }
        map.put("userid",users.getUserid(request));
        if (users.getUserid(request)==7){
            map.put("stats",4);
        }else{
            map.put("stats",0);
        }
        map.put("ustats",2);
        if(!StringUtil.isEmpty(request.getParameter("shipname"))) {
            map.put("shipname", request.getParameter("shipname"));
        }
        if (!StringUtil.isEmpty(request.getParameter("page"))){
            pageNum=Integer.parseInt(request.getParameter("page"));
        }
        PageHelper.startPage(pageNum,10);
        List<ShipInfo> shipInfosList =  shipInfoService.selectShipInfoListAndName(map);
        for(int i=0;i<shipInfosList.size();i++){
            String cname = FiledUtil.getAdd(shipInfosList.get(i).getDeviceInfo().getLongitude(),shipInfosList.get(i).getDeviceInfo().getLatitude());
            shipInfosList.get(i).getDeviceInfo().setCname(cname);
        }
        PageInfo pageInfo = new PageInfo(shipInfosList);
        Map mav = new HashMap();
        mav.put("pageInfo",pageInfo);
        mav.put("shipInfo",shipInfosList);
        return new ObjectMapper().writeValueAsString(mav);
    }



    //新增运输计划中查询船舶信息
    @RequestMapping(value = "/searchShipInfoByQuery.do")
    @ResponseBody
    public String searchShipInfosByQuery(HttpServletRequest request, @RequestParam(value = "page",defaultValue="1") Integer pageNum, @RequestParam(value = "shipname") String shipname) throws Exception{
        Map map =new HashMap();
        map.put("userid",users.getUserid(request));
        if(!StringUtil.isEmpty(shipname)) {
            map.put("shipname", shipname);
        }
        if (users.getUserid(request)==7){
            map.put("stats",4);
        }else{
            map.put("stats",0);
        }
        map.put("ustats",2);
        PageHelper.startPage(pageNum,10);
        List<ShipInfo> shipInfosList =  shipInfoService.selectShipInfoListAndName(map);
        for(int i=0;i<shipInfosList.size();i++){
            String cname = FiledUtil.getAdd(shipInfosList.get(i).getDeviceInfo().getLongitude(),shipInfosList.get(i).getDeviceInfo().getLatitude());
            shipInfosList.get(i).getDeviceInfo().setCname(cname);
        }
        PageInfo pageInfo = new PageInfo(shipInfosList);
        Map mav = new HashMap();
        mav.put("pageInfo",pageInfo);
        mav.put("shipInfo",shipInfosList);
        return new ObjectMapper().writeValueAsString(mav);
    }

    @RequestMapping("searchShipidListByQuery.do")
    @ResponseBody
    public String searchShipidListByQuery(@RequestParam(value = "ids") Integer[] ids) throws Exception{
        Map map = new HashMap();
        map.put("stats",1);
        map.put("ids",ids);
        shipInfoService.updateByShipidList(map);
        List<ShipInfo> list= shipInfoService.searchByShipidList(ids);
        for(int i=0;i<list.size();i++){
            String cname = FiledUtil.getAdd(list.get(i).getDeviceInfo().getLongitude(),list.get(i).getDeviceInfo().getLatitude());
            list.get(i).getDeviceInfo().setCname(cname);
        }
        return new ObjectMapper().writeValueAsString(list);
    }

    @RequestMapping("updateShipidByQuery.do")
    @ResponseBody
    public void updateShipidByQuery(@RequestParam(value = "shipid") Integer shipid,HttpServletRequest request)throws Exception{
        Map map = new HashMap();

        if (users.getUserid(request)==7){
            map.put("stats",4);
        }else{
            map.put("stats",0);
        }
        map.put("shipid",shipid);
        shipInfoService.updateShipByQuery(map);
    }



    @RequestMapping("addShipInfoByQuery.do")
    @ResponseBody
    public String addShipInfoByQuery(HttpServletRequest request)throws Exception{
        GoodsInfo goodsInfo = new GoodsInfo();
        TransportPlan transportPlan = new TransportPlan();
        String msg="";
        String goodsownername = request.getParameter("goodsownername");
        String goodsphone = request.getParameter("goodsphone");
        if (!StringUtil.isEmpty(goodsownername)&&!StringUtil.isEmpty(goodsphone)){
            goodsInfo = shipInfoService.selectGoodsInfoByQuery(goodsownername,goodsphone);
            if (goodsInfo == null){
                goodsInfo = new GoodsInfo();
                goodsInfo.setGoodsownername(request.getParameter("goodsownername"));
                goodsInfo.setGoodsphone(request.getParameter("goodsphone"));
                shipInfoService.addGoodsInfoByQuery(goodsInfo);
            }
            if (!StringUtil.isEmpty(request.getParameter("ordernumber"))){
                transportPlan.setOrdernumber(request.getParameter("ordernumber"));
            }
            if (!StringUtil.isEmpty(request.getParameter("goodsname"))){
                transportPlan.setGoodsname(request.getParameter("goodsname"));
            }
            if (!StringUtil.isEmpty(request.getParameter("totaltonnage"))){
                transportPlan.setTotaltonnage(Double.parseDouble(request.getParameter("totaltonnage")));
            }
            if (!StringUtil.isEmpty(request.getParameter("startdate"))){
                transportPlan.setStartdate(Timestamp.valueOf(request.getParameter("startdate")));
            }
            if (!StringUtil.isEmpty(request.getParameter("enddate"))){
                transportPlan.setEnddate(Timestamp.valueOf(request.getParameter("enddate")));
            }
            if (!StringUtil.isEmpty(request.getParameter("originating"))){
                transportPlan.setOriginating(request.getParameter("originating"));
            }
            if (!StringUtil.isEmpty(request.getParameter("destination"))){
                transportPlan.setDestination(request.getParameter("destination"));
            }
            if (!StringUtil.isEmpty(request.getParameter("scheduler"))){
                transportPlan.setScheduler(request.getParameter("scheduler"));
            }
            if (!StringUtil.isEmpty(request.getParameter("remarkes"))){
                transportPlan.setRemarkes(request.getParameter("remarkes"));
            }
            if (!StringUtil.isEmpty(request.getParameter("tid"))&&request.getParameter("tid") !=""){
                transportPlan.setGoodsid(goodsInfo.getGoodsid());
                transportPlan.setTransportid(Integer.parseInt(request.getParameter("tid")));
                shipInfoService.updateTransportPlanByQuery(transportPlan);
//                shipInfoService.deleteShipAndTranportByQuery(Integer.parseInt(request.getParameter("tid")));
                List<Integer> ytList =shipInfoService.selectShipAndTranportByShipid(Integer.parseInt(request.getParameter("tid")));
                JSONArray jsonArray =JSONArray.fromObject(request.getParameter("tabData"));
                List<Integer> xtList = new ArrayList<Integer>();
                for (int i=0;i<jsonArray.size();i++) {
                    xtList.add(Integer.parseInt(jsonArray.getJSONObject(i).getString("shipid")));
                }
                List<Integer> xzList = new ArrayList<Integer>(xtList);
                xzList.removeAll(ytList);
                List<Integer> yyList = new ArrayList<Integer>(ytList);
                yyList.removeAll(xtList);
                if (xzList.size()!=0&&xzList !=null) {
                    List<ShipAndTransport> stList = new ArrayList<ShipAndTransport>();
                    for (int j = 0; j < jsonArray.size(); j++) {
                        for (int k = 0; k < xzList.size(); k++) {
                            if (Integer.parseInt(jsonArray.getJSONObject(j).getString("shipid")) == xzList.get(k)) {
                                ShipAndTransport st = new ShipAndTransport();
                                st.setTransportid(Integer.parseInt(request.getParameter("tid")));
                                st.setShipid(Integer.parseInt(jsonArray.getJSONObject(j).getString("shipid")));
                                st.setAgentname(jsonArray.getJSONObject(j).getString("agentname"));
                                stList.add(st);
                            }
                        }
                    }
                    shipInfoService.addShipAndTranportByQuery(stList);
                }
                if (yyList.size()!=0 && yyList!=null){
                    Map map = new HashMap();
                    map.put("tid",Integer.parseInt(request.getParameter("tid")));
                    map.put("list",yyList);
                    shipInfoService.deleteShipAndTranportByQuery(map);
                }
            }else{
                transportPlan.setTanordernumber(RandomUtil.getOrdernumber(users.getUserid(request),goodsInfo.getGoodsid()));
                transportPlan.setCreationdate(new Timestamp((new Date()).getTime()));
                transportPlan.setStats(0);
                transportPlan.setGoodsid(goodsInfo.getGoodsid());
                transportPlan.setUserid(users.getUserid(request));
                shipInfoService.addTransportPlanByQuery(transportPlan);
                if (!StringUtil.isEmpty(request.getParameter("tabData"))) {
                    JSONArray jsonArray =JSONArray.fromObject(request.getParameter("tabData"));;
                    List<ShipAndTransport> stList = new ArrayList<ShipAndTransport>();
                    for (int i=0;i<jsonArray.size();i++){
                        ShipAndTransport st = new ShipAndTransport();
                        st.setShipid(Integer.parseInt(jsonArray.getJSONObject(i).getString("shipid")));
                        st.setAgentname(jsonArray.getJSONObject(i).getString("agentname"));
                        st.setTransportid(transportPlan.getTransportid());
                        stList.add(st);
                    }
                    shipInfoService.addShipAndTranportByQuery(stList);
                }else{
                    msg="船舶不能为空";
                    return new ObjectMapper().writeValueAsString(msg);
                }

            }
        }else{
            msg="货主姓名和电话不能为空！";
            return new ObjectMapper().writeValueAsString(msg);
        }
        return new ObjectMapper().writeValueAsString(true);
    }


    @RequestMapping("selectShipInfoCount.do")
    @ResponseBody
    public String selectShipInfoCountByQuery(HttpServletRequest request) throws Exception{
//        HttpSession session = request.getSession();
//        int userid = (int) session.getAttribute("userid");
        int ustats = 2;
        int count = shipInfoService.selectShipinfoCount(users.getUserid(request),ustats);
        return new ObjectMapper().writeValueAsString(count);
    }

    @RequestMapping("selectShipInfoByIsemityCount.do")
    @ResponseBody
    public String selectShipInfoByIsemityCountByQuery(HttpServletRequest request,@RequestParam(value = "isemtiy") int isemtiy) throws Exception{
        int isonline =0;
        int ustats = 2;
        int count = shipInfoService.selectShipinfoByIsemityCount(users.getUserid(request),isemtiy,isonline, ustats);
        return new ObjectMapper().writeValueAsString(count);
    }

    @RequestMapping("selectShipInfoByIsonlneCount.do")
    @ResponseBody
    public String selectShipInfoByIsonlneCountByQuery(HttpServletRequest request,@RequestParam(value = "isonline") int isonline) throws Exception{
        int ustats = 2;
        int count = shipInfoService.selectShipInfoByIsonlneCount(users.getUserid(request),isonline,ustats);
        return new ObjectMapper().writeValueAsString(count);
    }

    @RequestMapping(value = "/addTransport.do")
    @ResponseBody
    public void AddTrnasport(HttpServletRequest request)throws Exception{
        int ustats =2;
        List<ShipInfo> list = shipInfoService.selectShipInfoListByQuery(users.getUserid(request),ustats);
        List<ShipInfo> list1 = new ArrayList<ShipInfo>();
        for (int j=0;j<list.size();j++){
            if (list.get(j).getStats()==1){
                ShipInfo shipInfo = new ShipInfo();
                if(users.getUserid(request) == 7){
                    shipInfo.setStats(4);
                }else{
                    shipInfo.setStats(0);
                }

                shipInfo.setShipid(list.get(j).getShipid());
                list1.add(shipInfo);
            }
        }
        if (list1 !=null && list1.size() !=0){
            shipInfoService.updateShipInfoByList(list1);
        }
    }

    @RequestMapping("/searchShipInfoNotByUserid.do")
    @ResponseBody
    public String searchShipInfoNotByUserid(HttpServletRequest request, @RequestParam(value = "page",defaultValue="1") Integer pageNum, @RequestParam(value = "shipname") String shipname)throws Exception{

        Map map =new HashMap();
        List<ShipInfo> shipInfosList = new ArrayList<ShipInfo>();
        map.put("userid",users.getUserid(request));
        if(users.getUserid(request) == 7){
            map.put("stats",4);
            if(!StringUtil.isEmpty(shipname)) {
                map.put("shipname", shipname);
            }
            PageHelper.startPage(pageNum,10);
            shipInfosList =  shipInfoService.searchShipInfoNotByUserid(map);
            for(int i=0;i<shipInfosList.size();i++){
                String cname = FiledUtil.getAdd(shipInfosList.get(i).getDeviceInfo().getLongitude(),shipInfosList.get(i).getDeviceInfo().getLatitude());
                shipInfosList.get(i).getDeviceInfo().setCname(cname);
            }
        }else{
            map.put("stats",0);
            if(!StringUtil.isEmpty(shipname)) {
                map.put("shipname", shipname);
            }
            PageHelper.startPage(pageNum,10);
            shipInfosList =  shipInfoService.searchShipInfoNotByUserid(map);
            for(int i=0;i<shipInfosList.size();i++){
                String cname = FiledUtil.getAdd(shipInfosList.get(i).getDeviceInfo().getLongitude(),shipInfosList.get(i).getDeviceInfo().getLatitude());
                shipInfosList.get(i).getDeviceInfo().setCname(cname);
            }

        }
        PageInfo pageInfo = new PageInfo(shipInfosList);
        Map mav = new HashMap();
        mav.put("pageInfo",pageInfo);
        mav.put("shipInfo",shipInfosList);
        return new ObjectMapper().writeValueAsString(mav);
    }

    @RequestMapping("/addUserAndShip.do")
    @ResponseBody
    public String adduserandshipinfo(@RequestParam(value = "shipid")int shipid,HttpServletRequest request)throws Exception{
        UserAndShip userAndShip = new UserAndShip();
        userAndShip.setShipid(shipid);
        userAndShip.setUserid(users.getUserid(request));
        userAndShip.setUstats(1);
        userAndShip.setAddtime( new Date());
        shipInfoService.addUserAndShipInfo(userAndShip);
        return new ObjectMapper().writeValueAsString(true);
    }

    @RequestMapping("/searchUserAndShipinfo.do")
    @ResponseBody
    public String searchUserAndShipsinfo(HttpServletRequest request, @RequestParam(value = "page",defaultValue="1") Integer pageNum, @RequestParam(value = "shipname") String shipname)throws Exception {
        Map map =new HashMap();
        map.put("userid",users.getUserid(request));
        map.put("ustats",1);
        if(!StringUtil.isEmpty(shipname)) {
            map.put("shipname", shipname);
        }
        PageHelper.startPage(pageNum,10);
        List<ShipInfo> shipInfosList =  shipInfoService.searchUserAndShipsinfo(map);
        if ( shipInfosList !=null && shipInfosList.size()>0) {
            for (int i = 0; i < shipInfosList.size(); i++) {
                String cname = FiledUtil.getAdd(shipInfosList.get(i).getDeviceInfo().getLongitude(), shipInfosList.get(i).getDeviceInfo().getLatitude());
                shipInfosList.get(i).getDeviceInfo().setCname(cname);
            }
            PageInfo pageInfo = new PageInfo(shipInfosList);
            Map mav = new HashMap();
            mav.put("pageInfo", pageInfo);
            mav.put("shipInfo", shipInfosList);
            return new ObjectMapper().writeValueAsString(mav);
        } else{
            return new ObjectMapper().writeValueAsString(false);
        }
    }

    @RequestMapping("/selectUserinfoAndShipinfo.do")
    @ResponseBody
    public String selectUserinfoAndShipinfo( @RequestParam(value = "page",defaultValue="1") Integer pageNum, @RequestParam(value = "shipname") String shipname)throws Exception{
        Map maps = new HashMap();
        maps.put("shipname",shipname);
        maps.put("ustats",0);
        PageHelper.startPage(pageNum,10);
        List<UserAndShip> userAndShipList = shipInfoService.selectUserinfoAndShipinfo(maps);
        if (userAndShipList.size()>0&&userAndShipList!=null){
            PageInfo pageInfo = new PageInfo(userAndShipList);
            Map map = new HashMap();
            map.put("pageInfo", pageInfo);
            map.put("userAndShipList", userAndShipList);
            return new ObjectMapper().writeValueAsString(map);
        }else{
            return new ObjectMapper().writeValueAsString(false);
        }

    }

    @RequestMapping("/updateUserAndShipByUstats.do")
    @ResponseBody
    public String updateUserAndShipByUstats(@RequestParam(value = "shipid")int shipid,@RequestParam(value = "userid")int userid)throws Exception{
        Map map = new HashMap();
        map.put("shipid",shipid);
        map.put("userid",userid);
        map.put("ustats",2);
        shipInfoService.updateUserAndShipByUstats(map);
        return new ObjectMapper().writeValueAsString(true);
    }
}